package com.cn.wolf.bio;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author huangy
 * @since 2022/9/7 8:40 下午
 */
public class BIOServer {

    public static void main(String[] args) throws Exception {
        //1.创建线程池
        //2.如果客户端有连接，就创建一个线程与之通信
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动了...");
        while (true) {
            //监听等待客户端连接
            System.out.println("等待连接...");
            Socket socket = serverSocket.accept();
            //连接到另一个客户端
            //创建一个线程与之通信
            newCachedThreadPool.execute(() -> handler(socket));
        }


    }

    public static void handler(Socket socket) {
        try (InputStream inputStream = socket.getInputStream()) {
            System.out.println("线程id: " + Thread.currentThread().getId() + " 名称: " + Thread.currentThread().getName());
            byte[] datas = new byte[1024];
            while (true) {
                System.out.println("线程id: " + Thread.currentThread().getId() + " 名称: " + Thread.currentThread().getName());
                System.out.println("read...");
                int read = inputStream.read(datas);
                if (read != -1) {
                    System.out.println(new String(datas, 0, read));
                } else {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
